<script lang="ts" setup>
import bg_blue from '@/assets/instance/1.png'
import bg_green from '@/assets/instance/3.png'
import bg_red from '@/assets/instance/2.png'
import bg_1 from '@/assets/instance/大背景.png'
import bg_boder from '@/assets/instance/bg.png'
import { useDockerApiPath } from "@/stores/dockerApi";

import CompetitionTag from '@/components/competitionTag/competitionTag'
import Pages from '@/components/page'
import { APP_NAME } from '@/config/constants'
import { Course, usePortalQuery,useMyInfoQuery, Document, Instance, InstanceType, Maybe, Profile, Session, User } from '@/generated/graphql'
import { Route } from '@/router'
import { useUserStore } from '@/stores/auth'
import { useCourseSessionStore } from '@/stores/useCourseStore'
import { Session_store } from '@/stores/session'

import { useSession } from '@/stores/useSession'
import '@/styles/competition.scss'
import dayjs from 'dayjs'
import { cloneDeep, has } from 'lodash-es'
import { computed, onMounted,ref, reactive,nextTick, watchEffect } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { watch } from 'fs'
// 根据portal查询用户能够查看的课程信息
const authStore = useUserStore()
const userPortalId = authStore.user?.portal
const result = usePortalQuery({
  variables: {
    where: {
      id: userPortalId
    }
  }
})
//取出课程信息, 并展示出来
const { data: portal } = result
// console.log(portal);

const session_store=Session_store()
//颜色数组
const butcolors =  ['#266bd3', '#eb8611', '#17bab4']
const textcolors=['#2f6dc9','#db811a','#24b2ad']
const coursesByPortal = computed(() => {
  //是否是私有课程 如果是 就全部展示 ，否则根据课程中是否是published 来展示
  if (portal.value?.portal?.privatized) {
    return portal.value?.portal.courses
  } else {
    const _course = cloneDeep(portal.value?.portal?.courses)
    return _course?.filter((c: any) => c.published || (c.publishedAt !== null && dayjs().isAfter(dayjs(c.publishedAt))))
  }
})
//分页逻辑
const everyPageCount = 9
const startPage = ref(1)
const courses = computed(() => {
  window.scrollTo(0, 0)
  return coursesByPortal.value?.slice(
    (startPage.value - 1) * everyPageCount,
    everyPageCount + (startPage.value - 1) * everyPageCount
  )
})

const router = useRouter()
//locales
const { t, locale } = useI18n()

const getBackgroundImage = (index: number) => {
  const mod = index % 3
  const backgroundColors = [bg_green, bg_blue, bg_red]

  return backgroundColors[mod]
}

const course = useCourseSessionStore()
// 点击课程
function handleClick(item: Course) {
  console.log("进入课程");
  console.log(item);
  console.log(course);
  
  course.setCourse(item)
  course.setDocuments(item.documents)
  // 路由跳转
  router.push({
    name: Route.DETAIL
  })
}

/**
 * 站点设置
 */
/**设置banner 图片 */
const banners = import.meta.glob('../assets/banner/*.jpg', { eager: true })
const defaultBanner = `../assets/banner/default_${locale.value}.jpg`
const bannerName = `../assets/banner/${APP_NAME}_${locale.value}.jpg`
const defaultBannerName = computed(() => {
  if (portal?.value?.portal?.extends?.banner_paths) {
    return portal?.value?.portal?.extends?.banner_paths[locale.value]
  } else {
    return has(banners, bannerName) ? banners[bannerName] : banners[defaultBanner]
  }
})

//page 跳转
const handlePage = (pageHandle: Record<string, unknown>) => {  
  if (pageHandle.isappoint) {
    //指定页面
    startPage.value = pageHandle.page as number
  } else {
    const page = pageHandle.page as number
    startPage.value += page
  }
}

// const sessions = useSession()
// console.log(sessions);


const isshow= computed(()=>{
  return session_store.$state.isshow

})
//改后
const me = useMyInfoQuery();
    let session: Maybe<{ __typename?: "User" | undefined } & Pick<User, "id" | "createdAt" | "updatedAt" | "expiredAt" | "username" | "realName" | "enabled" | "portal" | "role"> & { profile?: Maybe<{ __typename?: "Profile" | undefined } & Pick<Profile, "id" | "createdAt" | "updatedAt" | "bio">> | undefined; session?: Maybe<{ __typename?: "Session" | undefined } & Pick<Session, "id"> & { course: { __typename?: "Course" | undefined } & Pick<Course, "id" | "extends" | "title" | "description" | "cover">; document: { __typename?: "Document" | undefined } & Pick<Document, "id" | "extends" | "title" | "description">; instances: ({ __typename?: "Instance" | undefined } & Pick<Instance, "id" | "platformType" | "platformDetails"> & { private: any } & { instanceType?: Maybe<{ __typename?: "InstanceType" | undefined } & Pick<InstanceType, "enabled" | "series" | "size" | "vCPUs" | "cores" | "memorySize" | "storageSize" | "storageType" | "networkPerformance" | "hypervisor" | "architecture" | "onDemandLinuxPricing" | "onDemandWindowsPricing" | "onStoragePricing">> | undefined })[] }> | undefined }> | undefined =null;
    onMounted(async () => {
      console.log("获取sesssion");
      
      console.log(session_store.$state.isshow); 
      await me.data.value?.me;
    });

    watchEffect(async () => {
      if (me.data.value) {
        session = me.data.value?.me;
        console.log(session);
        
        if(session?.session){
          session_store.$state.isshow=true
        //新添加：连接doker的ip
    const sessionip = session.session;
    const ipAddress =
    sessionip.instances[0]?.private?.addresses["network-public"][0]?.addr ??
      "docker-none";
    // session 存在可以通过session 去查询里面的docker容器信息，这个时候需要把docker api换成该容器的地址
    const dockerAPIStore = useDockerApiPath();
    dockerAPIStore.setRouter(ipAddress);

  
}
        await nextTick();
      
        
      }
    });

</script>

<template>
  <div id="competition" class="flex flex-col items-center "
    :style="{ 'background': `url(${bg_1})`, 'background-color': '#20252f' }">
    <div :style="{ 'width': '100 % ', 'borderRadius': '2% ', 'margin': 'auto', 'background': `url(${bg_1})` }">

      <div class="w-full mb-8 h-120">
        <img :src="defaultBannerName.default" alt="" class="w-full h-120" />
      </div>
      <div class="flex flex-col justify-center w-full my-6">
        <CompetitionTag v-if="isshow" />
        <!-- <CompetitionTag  /> -->

      </div>

      <div class="relative w-full mt-6 text-center h-15">
        <p class="absolute text-5xl font-bold transform -translate-x-1/2 left-1/2 bottom-7.5" style="color: #1a2b53">
          COURSESLISTS
        </p>

        <p style="color: #e0ecf6;font-family: 微软雅黑;font-weight: 900;" class="absolute text-3xl font-medium transform -translate-x-1/2 text-fonts-300 left-1/2 bottom-7.4">
          {{ t('competition.title') }}
        </p>
      </div>

      <a-divider style="width: 32.5rem"></a-divider>

      <p v-if="!result.fetching || (coursesByPortal && coursesByPortal.length <= 0)"
        class="w-full py-2 text-center text-gray-400">
        {{ t('competition.noCourse') }}
      </p>
      <div v-if="!coursesByPortal" class="flex mx-auto mt-4 space-x-5 w-350 h-80">
        <div v-for="i in 3" class="w-1/3 overflow-hidden rounded-md">
          <a-skeleton height="16.625rem" width="100%" />
        </div>
      </div>
      <section v-if="coursesByPortal" id="competition" class="grid grid-cols-3 gap-4 m-2 w-4/5">
        <div v-for="(item, index) in courses" class=" relative flex-shrink-0 max-w-115 rounded-lg">
          <div class=" relative flex-shrink-0 max-w-115 rounded-lg" :style="{
            height: '29rem',
            backgroundImage: `url(${bg_boder})`,
            backgroundRepeat: 'no-repeat',
            backgroundSize: 'cover',
            padding: '1rem'
          }">

            <div style="background-color: #262626;"
              class="flex flex-col overflow-hidden transition duration-300 ease-in-out transform bg-white border border-gray-100 border-solid rounded-lg group">
              <div class="relative">
                <div class="w-full h-66.5 overflow-hidden border-b-1 object-cover relative">
                  
                  <img :src="item.cover" class="absolute w-full h-full" />
                  <img :src="getBackgroundImage(index + 1)" class="absolute w-full h-full" />
                </div>
                <div
                  class="absolute overflow-hidden text-3xl text-white whitespace-nowrap overflow-ellipsis top-20 left-10">
                  <div class="mt-2" :style="{'color': `${textcolors[index % textcolors.length]}`, 'font-size': '4rem', 'font-family': '微软雅黑','font-weight': '900'}">大数据技术</div>

                <div style="font-weight: 900;">
                  {{ item.title }}
                </div>
                  <a-divider style="border-color: #fff; width: 3rem;"  ></a-divider>
                </div>

              </div>
              <div class="relative flex items-center h-20 text-sm text-fonts-400 text-white">
                <!-- <p class="px-5" style="
                 {
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                }
              ">
                  {{ item.description }}
                </p> -->
                <!-- <div
                  class="absolute flex items-center w-full h-full px-5 duration-75 bg-gray-400 cursor-pointer top-20 group-hover:top-0 translation opacity-95"
                  @click="handleClick(item as any)">
                  <p class="flex items-center text-lg font-bold text-white">
                    {{ t('competition.start') }}
                    <span class="iconify" data-icon="bx:bx-fast-forward" data-inline="false" />
                  </p>
                </div> -->
                <div class=" w-full flex text-white   justify-around " style="font-family:微软雅黑;margin-top:-5rem ;">
                  <div style="font-size: 1.5rem;">{{ $t('vuetitle.title') }}</div>
                  <div
                    :style="{'font-size': '1.2rem','background-color': `${butcolors[index % butcolors.length]}`,'border-radius': '6px','width': '4rem','height': '1.7rem','text-align': 'center','line-height': '1.7rem','cursor': 'pointer'}"
                    @click="handleClick(item as any)"
                    >
                    {{ $t('competition.start') }}
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </section>
      <div class="flex items-center justify-center w-full py-5">
        <template v-if="coursesByPortal">
          <Pages :courses="coursesByPortal" :every-page-count="everyPageCount" @handlePage="handlePage" />
        </template>
      </div>
    </div>

  </div>
</template>
